<?php

namespace app\proxy\model\product;

use app\common\model\region\Region as Region1;
use app\proxy\model\proxy\Region;
use \app\common\model\product\Category as BaseCategory;

/**
 * 产品分类模型
 */
class Category extends BaseCategory
{

    /**
     * 获取列表
     * @param $param
     * @param $regionIds
     * @param int $proxyId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @Author joey
     * @date 2024/3/28 11:38
     */
    public static function getProxyALL($param, $regionIds, $proxyId = 0)
    {
        // 20240327 joey 修改分类数据不做缓存，因为页面切换时数据不改变
        $model = new static;
        $data = $model->with(['images'])
            ->when($param, function ($query) use ($param) {
                $query->where($param);
            })
            ->where(function ($query) use ($regionIds) {
                $query->whereIn('county_id', $regionIds)->whereOr("province_id", "in", $regionIds)->whereOr("city_id", "in", $regionIds);
            })
            ->order(['sort' => 'asc', 'create_time' => 'asc'])
            ->select();

        $all  = !empty($data) ? $data->toArray() : [];
        $tree = [];
        foreach ($all as $first) {
            if ($first['parent_id'] != 0) continue;
            if ($proxyId > 0) {
                $region_id = $first["province_id"];
                if ($first["city_id"]) {
                    $region_id = $first["city_id"];
                }
                if ($first["county_id"]) {
                    $region_id = $first["county_id"];
                }
                $first["region_name"] = Region1::getMergerName($region_id);
                $first["proxy_name"]  = Region::getProxyName($first, $proxyId);
                $first["can_edit"]    = $first["proxy_id"] == $proxyId ? 1 : 0;
            }
            $twoTree = [];
            foreach ($all as $two) {
                if ($two['parent_id'] != $first['category_id']) continue;
                if ($proxyId > 0) {
                    $region_id = $two["province_id"];
                    if ($two["city_id"]) {
                        $region_id = $two["city_id"];
                    }
                    if ($two["county_id"]) {
                        $region_id = $two["county_id"];
                    }
                    $two["region_name"] = Region1::getMergerName($region_id);
                    $two["proxy_name"]  = Region::getProxyName($two, $proxyId);
                    $two["can_edit"]    = $two["proxy_id"] == $proxyId ? 1 : 0;
                }
                $threeTree = [];
                foreach ($all as $three) {
                    $three['parent_id'] == $two['category_id']
                    && $threeTree[$three['category_id']] = $three;
                    if ($proxyId > 0) {
                        $region_id = $three["province_id"];
                        if ($three["city_id"]) {
                            $region_id = $three["city_id"];
                        }
                        if ($three["county_id"]) {
                            $region_id = $three["county_id"];
                        }
                        $three["region_name"] = Region1::getMergerName($region_id);
                        $three["proxy_name"]  = Region::getProxyName($three, $proxyId);
                        $three["can_edit"]    = $three["proxy_id"] == $proxyId ? 1 : 0;
                    }
                }
                !empty($threeTree) && $two['child'] = $threeTree;
                array_push($twoTree, $two);
            }
            if (!empty($twoTree)) {
                $temp_two_tree = array_column($twoTree, 'sort');
                array_multisort($temp_two_tree, SORT_ASC, $twoTree);
                $first['child'] = $twoTree;
            }
            array_push($tree, $first);
        }

        return compact('all', 'tree');
    }


    /**
     * 获取分类树形结果
     * @param $param
     * @param $regionIds
     * @param $proxyId
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @Author joey
     * @date 2024/3/28 11:48
     */
    public static function getProxyCategoryTree($param, $regionIds, $proxyId = 0)
    {
        return self::getProxyALL($param, $regionIds, $proxyId)['tree'];
    }

    /**
     * 获取所有一级分类
     */
    public static function getProxyFirstCategory($proxy_id)
    {
        return (new static())->where('parent_id', '=', 0)
            ->where('proxy_id', '=', $proxy_id)
            ->order(['sort' => 'asc', 'create_time' => 'asc'])
            ->select();
    }

    /**
     * 添加新记录
     */
    public function add($data, $proxy_id)
    {
        $data['app_id']      = self::$app_id;
        $data['proxy_id']    = $proxy_id;
        $data['province_id'] = $data["region_id"][0] ?? 0;
        $data['city_id']     = $data["region_id"][1] ?? 0;
        $data['county_id']   = $data["region_id"][2] ?? 0;
        unset($data["region_id"]);
        return $this->save($data);
    }

    /**
     * 编辑记录
     */
    public function edit($data, $proxyId)
    {
        $data["audit_status"] = $data['audit_status'] ?? 0;
        $data['province_id']  = $data["region_id"][0] ?? 0;
        $data['city_id']      = $data["region_id"][1] ?? 0;
        $data['county_id']    = $data["region_id"][2] ?? 0;
        unset($data["region_id"]);

        if ($proxyId != $this["proxy_id"]) {
            $this->error = "你无权修改此分类";
            return false;
        }

        // 验证：一级分类如果存在子类，则不允许移动
        if ($data['parent_id'] > 0 && static::hasSubCategory($this['category_id'])) {
            $this->error = '该分类下存在子分类，不可以移动';
            return false;
        }
        !array_key_exists('image_id', $data) && $data['image_id'] = 0;
        return $this->save($data) !== false;
    }

    /**
     * 删除商品分类
     */
    public function remove($categoryId)
    {
        // 判断是否存在商品
        if ($productCount = (new Product)->getProductTotal(['category_id' => $categoryId])) {
            $this->error = '该分类下存在' . $productCount . '个商品，不允许删除';
            return false;
        }
        // 判断是否存在子分类
        if (static::hasSubCategory($categoryId)) {
            $this->error = '该分类下存在子分类，请先删除';
            return false;
        }
        return $this->delete();
    }

}
